package com.drm.netschool.service;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.drm.common.util.DateUtil;
import com.drm.common.util.EncryptTool;
import com.drm.common.util.IdCreater;
import com.drm.common.util.Saltcheckutil;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.entity.DrmUserExample;
import com.drm.netschool.entity.extend.UserInfo;
import com.drm.netschool.mapper.DrmUserMapper;
import com.drm.netschool.mapper.manual.DrmUserExtendMapper;

@Service
public class DrmUserService {

	private Logger LOGGER = LoggerFactory.getLogger(DrmUserService.class);

	@Autowired
	private DrmUserMapper userMapper;
	
	@Autowired
	private DrmUserExtendMapper extendMapper;

	public DrmUser getById(long userId) {
		return userMapper.selectByPrimaryKey(userId);
	}
	
	public DrmUser getByUserName(String userName) {
		DrmUserExample example = new DrmUserExample();
		example.createCriteria().andUserLnmEqualTo(userName);
		List<DrmUser> list = userMapper.selectByExample(example);
		if (list == null || list.size() == 0)
			return null;
		return list.get(0);
	}
	
	public DrmUser getByUserNameAndEmail(String userName, String email){
		DrmUserExample example = new DrmUserExample();
		example.createCriteria().andUserLnmEqualTo(userName).andUserEmailEqualTo(email);
		List<DrmUser> list = userMapper.selectByExample(example);
		if (list == null || list.size() == 0)
			return null;
		return list.get(0);
	}
	
	public DrmUser login(String userName, String password){
		DrmUser user = getByUserName(userName);
		if(user == null)
			return null;
		
		String pwd = Saltcheckutil.saltArithmetic(password, user.getUserSalt());
		
		return pwd.equals(user.getUserPass()) ? user : null;
	}
	
	public int resetPassword(Long userId, String password){
		DrmUser user = getById(userId);
		if(user == null)
			return 0;
		
		DrmUserExample example = new DrmUserExample();
		example.createCriteria().andUserIdEqualTo(userId);
		user.setUserPass(Saltcheckutil.saltArithmetic(password, user.getUserSalt()));
		user.setUserUdt(DateUtil.current());
		return userMapper.updateByExample(user, example);
	}

	public long addUser(DrmUser user) {
		if (user == null)
			return 0;

		long userId = IdCreater.getId();
		String salt = getSalt();
		user.setUserRnm(user.getUserLnm());
		user.setUserDesc("");
		user.setUserSalt(salt); // 密码种子
		user.setUserPass(Saltcheckutil.saltArithmetic(user.getUserPass(), salt)); // 使用密码种子加密密码
		user.setUserId(userId);
		user.setUserTp(5); // 5 代表注册用户
		user.setUserUyn(1); // 是否使用， 0表示不使用，1表示使用
		user.setUserSource(0); // 用户来源，0，自己注册； 1，网校；2，代理商；3，分校
		user.setUserAvtive(0); // 默认0 未激活，不能登陆系统，1位激活， 代理商管理员创建的用户都为1
		user.setUserLock(0); // 0 未锁定，1锁定， 锁定后暂时不能进入，需要等待一段时间
		user.setUserSourceid(-9L); // -9标志 用户自己注册的 ，和别人无关的，
		user.setUserCdt(DateUtil.current());
		user.setUserUdt(DateUtil.current());
		userMapper.insertSelective(user);
		LOGGER.info(user.getUserLnm() + ",注册完成!");
		return userId;
	}
	
	public int updateUser(DrmUser user){
		if(user == null)
			return 0;
		
		user.setUserUdt(DateUtil.current());
		return userMapper.updateByPrimaryKey(user);
	}
	
	public int getSortUserInfoCount(UserInfo userInfo){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", userInfo);
		return extendMapper.getSortUserInfoCount(param);
	}
	
	public List<UserInfo> getSortUserInfoList(UserInfo userInfo, Integer page, Integer pageSize){
		int start = (page - 1) * pageSize;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", userInfo);
		param.put("offset", start);
		param.put("limit", pageSize);
		return extendMapper.getSortUserInfoList(param);
	}
	
	public List<UserInfo> getUserInfoList(UserInfo userInfo, Integer page, Integer pageSize){
		int start = (page - 1) * pageSize;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", userInfo);
		param.put("offset", start);
		param.put("limit", pageSize);
		return extendMapper.getUserInfoList(param);
	}
	
	public UserInfo getUserInfoList(Long userId){
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(userId);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", userInfo);
		List<UserInfo> list = extendMapper.getUserInfoList(param);
		return list == null || list.isEmpty() ? null : list.get(0);
	}
	
	public int getUserInfoCount(UserInfo userInfo){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", userInfo);
		return extendMapper.getUserInfoCount(param);
	}
	
	public int getCount(DrmUser entity){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", entity);
		return extendMapper.getCount(param);
	}
	
	public List<DrmUser> getListByPage(DrmUser entity, int page, int pageSize){
		int start = (page - 1) * pageSize;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("param", entity);
		param.put("offset", start);
		param.put("limit", pageSize);
		return extendMapper.getListByPage(param);
	}
	
	public List<UserInfo> getRecommendUserInfoList(){
		return extendMapper.getRecommendUserInfoList();
	}
	
	/****************private*****************/
	/**
	 * 生成密码种子
	 * @return
	 */
	private String getSalt(){
		String salt = "";
		try {
			salt = EncryptTool.md5Hex(EncryptTool.sha1HEX(DateUtil.dateToStr(DateUtil.current(), DateUtil.FORMAT_DEFAULT_MIN)));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
		}
		return salt;
	}
}
